package com.baosight.risk.service.riim.impl;

import com.baosight.risk.api.riim.RiimRiskEvaluationService;
import com.baosight.risk.base.service.BaseServiceImpl;
import com.baosight.risk.common.bean.BeanUtils;
import com.baosight.risk.common.utils.StringUtils;
import com.baosight.risk.mapper.riim.RiimRiskEvaluationMapper;
import com.baosight.risk.service.riim.entity.RiimRiskEvaluation;
import groovy.util.logging.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author RayWade
 * @create 2019 - 08 - 20 14:57
 */
@Service
@Slf4j
public class RiimRiskEvaluationServiceImpl extends BaseServiceImpl<RiimRiskEvaluation>
        implements RiimRiskEvaluationService {

    @Autowired
    private RiimRiskEvaluationMapper evaluationMapper;


    @Override
    public Integer saveEvaluation(RiimRiskEvaluation evaluation) {
        if (StringUtils.isNotEmpty(evaluation.getId())) {
            evaluation = (RiimRiskEvaluation) BeanUtils.updateBean(evaluation);
            return update(evaluation);
        } else {
            Integer rowOrder;
            Integer maxRowOrder = evaluationMapper.queryMax(evaluation.getImportGuid());
            if (maxRowOrder == null) {
                rowOrder = 1;
            } else {
                rowOrder = Integer.valueOf(maxRowOrder) + 1;
            }
            evaluation.setRowOrder(rowOrder);
            evaluation = (RiimRiskEvaluation) BeanUtils.initBean(evaluation);
            return evaluationMapper.insert(evaluation);
        }
    }

    @Override
    public Integer deleteEvaluation(List<String> ids) {
        ids.forEach(id -> {
            evaluationMapper.deleteByPrimaryKey(id);
        });
        return 1;
    }

    @Override
    public void updateRowOrder(RiimRiskEvaluation evaluation) {
        List<RiimRiskEvaluation> evaluationList = evaluationMapper.selectByImportGuid(evaluation.getImportGuid());
        if (CollectionUtils.isNotEmpty(evaluationList)) {
            List<String> ids = evaluationList.stream().map(RiimRiskEvaluation::getId).collect(Collectors.toList());
            RiimRiskEvaluation evaluation1 = get(evaluation.getId());
            int i = ids.indexOf(evaluation.getId());
            if ("up".equals(evaluation.getExt1())) {
                i--;
            } else {
                i++;
            }
            if(i < ids.size() && i >= 0){
                RiimRiskEvaluation evaluation2 = get(ids.get(i));
                int rowOrder1 = evaluation1.getRowOrder();
                int rowOrder2 = evaluation2.getRowOrder();
                evaluation1.setRowOrder(rowOrder2);
                update(evaluation1);
                evaluation2.setRowOrder(rowOrder1);
                update(evaluation2);
            }
        }
    }
}
